package cn.ycbjie.ycaudioplayer.newpack.linkagescroll.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.synjones.minnovate.frame.basesdk.http.SynHttp;
import com.synjones.minnovate.frame.basesdk.http.SynSchedulersTranfs;
import com.synjones.minnovate.frame.basesdk.http.exception.AbsRxSubscriber;
import com.synjones.minnovate.frame.basesdk.http.exception.ApiException;
import com.synjones.minnovate.frame.basesdk.log.SynLog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.ycbjie.ycaudioplayer.R;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.MyPlayerActivity;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.NestScrollingActivitynew;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.BaseAdapter;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.BaseDelegate;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.BaseViewHolder;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter.RecyclerBaseAdapter3;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.iapiserver.iapi;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.mybeans.MyPlayerlistBean;
import cn.ycbjie.ycaudioplayer.ui.music.local.model.AudioMusic;
import cn.ycbjie.ycaudioplayer.ui.music.onLine.model.bean.OnlineMusicList;

import static cn.ycbjie.ycaudioplayer.newpack.linkagescroll.config.MyConfig.baseURL;

/**
 * Created by hzsunyj on 2017/12/18.
 */

@SuppressLint("ValidFragment")
public class TabFragment extends Fragment {

    RecyclerView recyclerView;

    private List<String> datas;
    private String listid;
    private Context mcontext;
    private String picurl;
    protected RecyclerBaseAdapter3 recyclerBaseAdapter;
    final ArrayList<MyPlayerlistBean> lcs = new ArrayList<MyPlayerlistBean>();

    @SuppressLint("ValidFragment")
    public TabFragment(String id,Context context,String picurl) {
        this.listid = id;
        this.mcontext = context;
        this.picurl =picurl;

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        return inflater.inflate(R.layout.fragment_tab_layout, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        findViews();
        init();
    }

    private void findViews() {
        recyclerView = getView().findViewById(R.id.list);
    }

    private void init() {
        getDatas();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(mcontext, DividerItemDecoration.VERTICAL));
        String id = listid;
        String limit = "";
        String page = "1";
        getplayererlist(id, limit, page, true);
    }

    private class StringViewHolder extends BaseViewHolder<String> {


        private TextView textView;

        /**
         * @param parent current no use, may be future use
         * @param view
         */
        public StringViewHolder(ViewGroup parent, View view) {
            super(parent, view);
        }

        @Override
        public void findViews() {
            textView = itemView.findViewById(R.id.content);
        }

        @Override
        public void onBindViewHolder(String data) {
            textView.setText(data);
        }
    }

    private void getDatas() {
        datas = new ArrayList<>();
        for (int i = 0; i < 20; ++i) {
            datas.add("content" + i);
        }
    }

    private void getplayererlist(final String id, final String limit, final String page, final Boolean isfirst) {

        SynHttp.getInstance().getApi(baseURL, iapi.class).getListmp3(id, limit, page)
                .compose(SynSchedulersTranfs.<String>schedulersTransformer())
                .subscribe(new AbsRxSubscriber<String>() {
                    @Override
                    public void onRxError(ApiException ex) {
                        SynLog.file(ex.getDisplayMessage());
                    }


                    public void onNext(String weatherInfoBean) {

                        try {
                            JSONObject obj = new JSONObject(weatherInfoBean.toString());
                            String code = obj.getString("code");
                            String data = obj.getString("data");

                            JSONObject objer = new JSONObject(data);
                            JSONArray jsonArray = objer.getJSONArray("data");
                            String dataer = objer.getString("data");
                            int total = Integer.parseInt(objer.getString("total"));
                            int limit = 100;//Integer.parseInt(objer.getString("limit"));
                            int pp = total / limit + 1;
                            Gson gson = new Gson();
                            JsonParser parser = new JsonParser();
                            JsonArray Jarray = parser.parse(dataer).getAsJsonArray();
                            for (JsonElement objel : Jarray) {
                                MyPlayerlistBean cse = gson.fromJson(objel, MyPlayerlistBean.class);
                                lcs.add(cse);

                            }
                            if (isfirst) {
                                recyclerBaseAdapter = new RecyclerBaseAdapter3(getActivity(), lcs);

//                                recyclerBaseAdapter = new RecyclerBaseAdapter3(getActivity(), dataList);
                                recyclerBaseAdapter.setOnItemClickListener(new RecyclerBaseAdapter3.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(View view, int position) {
                                        recyclerBaseAdapter.setDefSelect(position);
                                        TextView tv = view.findViewById(R.id.tv_playerlist_id);
                                        TextView tvpic = view.findViewById(R.id.tv_playerlist_pic);
                                        String ids = tv.getText().toString();
                                        String pic = tvpic.getText().toString();
                                        String titles = lcs.get(position).getTitle();

                                        OnlineMusicList.OnlineMusic onlineMusic = new OnlineMusicList.OnlineMusic();
                                        onlineMusic.setTitle("测试数据数据");
                                        onlineMusic.setSong_id(ids);
                                        onlineMusic.setPic_big(pic);
                                        List<AudioMusic> ls = new ArrayList<AudioMusic>();

                                        long du =lcs.get(position).getDuration();
//                                        AudioMusic audioMusic = new AudioMusic();
//                                        audioMusic.setArtist("ccc");
//                                        audioMusic.setCoverPath(pic);
//                                        audioMusic.setPath("http://fdfs.xmcdn.com/group19/M00/3B/21/wKgJK1ePRjLwvXl0AAy74JiGcgw431.mp3");
//                                       ls.add(audioMusic);
//                                       getPlayService().play(audioMusic,position);
//                                        playbyid(position, true);
//                                     playMusic(onlineMusic);
                                        Intent intent = new Intent();
                                        intent.setClass(mcontext, NestScrollingActivitynew.class);
                                        intent.putExtra("id",id);
                                        intent.putExtra("title",titles);
                                        intent.putExtra("picurl",picurl);
                                        intent.putExtra("summary",du);
                                        intent.putExtra("listid",id);
                                        intent.putExtra("created","2018-11-07T15:04:45.749Z");

//                                        myid = intent.getStringExtra("id");
//                                        title  = intent.getStringExtra("title");
//                                        picurl= intent.getStringExtra("picurl");
//                                        created= stampToDate(intent.getStringExtra("created"));
//                                        summary = intent.getStringExtra("summary");
                                        startActivity(intent);
                                        Toast.makeText(getActivity(), "click " + position + "-" + ids, Toast.LENGTH_SHORT).show();
                                    }
                                });
//                                recyclerBaseAdapter.setOnItemLongClickListener(new RecyclerBaseAdapter3.OnItemLongClickListener() {
//                                    @Override
//                                    public void onItemLongClick(View view, int position) {
//                                        Toast.makeText(getActivity(),"long click "+position,Toast.LENGTH_SHORT).show();
//                                    }
//                                });
                                recyclerView.setAdapter(recyclerBaseAdapter);
                            } else {
//                                //添加数据到列表的底部
//
//                                if(pp<Integer.parseInt(page))
//                                {
//                                    //没有加载更多了
//                                    adapterlist.changeMoreState(adapterlist.NO_LOAD_MORE);
//                                }
//
//                                else
//                                {
//                                    adapterlist.addFootItem(lcs);
//
//                                    //设置回到上拉加载状态
//                                    adapterlist.changeMoreState(adapterlist.PULLUP_LOAD_MORE);
//
//
//                                    Toast.makeText(mcontext, "上拉更新了" + lcs.size() + "条数据", Toast.LENGTH_SHORT).show();
//                                }
                            }
//                            if (adapterlist==null) {
//                                dropListView = (DropListView) findViewById(R.id.list_view_id);
//                                lv.setInterface(test_musicplayer.this);//设置回调接口
//                            adapterlist = new MyFinderAdapter(mcontext, lcs);
//                                lv.setAdapter(adapterlist);
//                            }else {
//                                adapterlist.onDateChange();
//                            }

//                            adapterlist = new MyAdapter(test_musicplayer.this, lcs);
//                            lv.setInterface(test_musicplayer.this);//设置回调接口

//                            ref_finderlist.setAdapter(adapterlist);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        SynLog.file("String----->" + weatherInfoBean.toString());
                    }
                });

    }
}
